<!--
 * @Date: 2020-09-18 07:56:57
 * @LastEditors: 小枫
 * @LastEditTime: 2020-09-19 12:50:19
 * @FilePath: \vue3-camp\src\App.vue
-->
<template>
  <!-- <div>
    <input type="text" v-model="val" @keyup.enter="addTodos" />
    <ul>
      <li v-for="todo in todos" :key="todo.id">{{todo.name}}</li>
    </ul>
    {{countPro}}
  </div> -->
  {{count}}
  <button @click="count++">click</button>
</template>

<script>
import { ref, reactive, toRefs, watch, toRef, computed } from "vue";
export default {
  setup() {
    let { addTodos, state } = todoDemo();
    let count = ref(1);

    let data = reactive({
      name: "张三",
      age: 13,
    });

    let ageRef = toRef(data, "age");

    watch(count, (count, prevCount) => {
      console.log("new:" + count);
      console.log("old:" + prevCount);
    });
    // watch(() => data.age, (age, prevAge) => {
    //   console.log("new:" + age);
    //   console.log("old:" + prevAge);
    // })
    watch([
      () => data.name,
      () => data.age],
      ([name, age], [prevName, prevAge]) => {
        console.log(name);
        console.log(age);
        console.log('---------');
        console.log(prevName);
        console.log(prevAge);
    })
    const countPro = computed(() => {
      return "count:" + count.value;
    });
    function add() {
      // count.value++;
      data.age++
      // console.log(ageRef.value);
    }
    return {
      count,
      add,
      addTodos,
      countPro,
      ...toRefs(state),
    };
  },
  // data() {
  //   return {
  //     number: 1
  //   }
  // },
  // methods: {
  //   add() {
  //     this.number++
  //   }
  // },
};
function todoDemo() {
  let state = reactive({
    todos: [
      { id: 0, name: "学习" },
      { id: 1, name: "玩游戏" },
    ],
    val: "",
  });

  function addTodos() {
    state.todos.push({
      id: state.todos.length,
      name: state.val,
    });
    state.val = "";
  }

  return { addTodos, state };
}
function testToRef() {
  return ageRef;
}
</script>
